//
//  XPHomeViewController.swift
//  SinaWeibo
//
//  Created by 徐攀 on 16/5/9.
//  Copyright © 2016年 徐攀. All rights reserved.
//

import UIKit

let reuseIdentifier = "homeCell"

class XPHomeViewController: XPVisitorViewController {
    /// 绑定首页tableView数据viewModel
    lazy var statusesList: XPStatusesListViewModel = XPStatusesListViewModel()
    
    // MARK: - 懒加载UI控件
    /// 下拉刷新控件
    private lazy var pullDownView: XPRefreshControl = XPRefreshControl()
    /// 上拉加载控件
    private lazy var dragUpView: UIActivityIndicatorView = {
        let accessoryView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        accessoryView.sizeToFit()
        accessoryView.hidesWhenStopped = true
        return accessoryView
    }()
    /// 刷新成功后的提示文本
    private lazy var tipsLabel: UILabel = {
        let tipsLabel = UILabel(color: UIColor.whiteColor(), fontSize: 12)
        tipsLabel.backgroundColor = UIColor.orangeColor()
        tipsLabel.textAlignment = .Center
        tipsLabel.sizeToFit()
        return tipsLabel
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 判断是否处于登录状态
        if isLogin {
            
            setupTitleView()
            setupTableView()
            // 请求数据
            loadMoreData(false, isPullDown: false)

        }else {
            // 加载访客视图
            visitorView?.visitorInfo(nil, imageName: nil)
        }
    }
    
    // MARK: - 加载数据
    func loadMoreData(isPullUp: Bool, isPullDown: Bool) {
        
        if isPullUp {dragUpView.startAnimating()}
        
        guard let accessToken = XPUserAccountViewModel.defaultUserAccount.userAccount?.access_token else {
            return
        }
        statusesList.requestStatuses(accessToken, isPullUp:isPullUp, complete: { (isSuccess, tips) -> () in
            if isSuccess {
                self.tableView.reloadData()
                
                // 请求成功后上拉加载和下拉刷新均结束
                self.pullDownView.endRefreshing()
                if self.tipsLabel.hidden && isPullDown {
                    // 提示消息动画
                    self.startTipsAnimaiton(tips)
                } else if isPullUp {
                    self.dragUpView.stopAnimating()
                }
            }
        })
    }
    
    private func setupTitleView() {
        let titleBtn = UIButton(title: XPUserAccountViewModel.defaultUserAccount.userAccount!.name!, fontSize: 14, backgoundImg: "common_button_white_disable", target: nil, action: nil)
        titleBtn .setTitleColor(UIColor.darkTextColor(), forState: .Normal)
        navigationItem.titleView = titleBtn
    }
    
    // MARK: - 初识化tableView
    private func setupTableView() {
        
        tableView.registerClass(XPStatuesCell.self, forCellReuseIdentifier: reuseIdentifier)
        tableView.estimatedRowHeight = 200
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.separatorStyle = .None
        tableView.tableFooterView = dragUpView;
        
        pullDownView.addTarget(self, action: #selector(XPHomeViewController.pullDownLoadMore), forControlEvents: .ValueChanged)
        tableView.addSubview(pullDownView)
        
        if let nav = navigationController {
            tipsLabel.hidden = true
            tipsLabel.frame = CGRectMake(0, 64 - 30, screenWidth, 30)
            nav.view.insertSubview(tipsLabel, belowSubview: nav.navigationBar)
        }
        
    }
    // MARK: - 下拉刷新事件
    @objc private func pullDownLoadMore() {
        loadMoreData(false, isPullDown: true)
    }
    // MARK: - 提示动画
    private func startTipsAnimaiton(tips: String) {
        
        self.tipsLabel.hidden = false
        self.tipsLabel.text = tips
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.tipsLabel.transform = CGAffineTransformMakeTranslation(0, 30)
            }) { (_) -> Void in
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    
                    UIView.animateWithDuration(0.5, animations: { () -> Void in
                        self.tipsLabel.transform = CGAffineTransformIdentity
                        }, completion: { (_) -> Void in
                            self.tipsLabel.hidden = true
                    })
                })
        }
    }
}

// MARK: - UITableViewDataSource
extension XPHomeViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusesList.statusesCell?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier, forIndexPath: indexPath) as! XPStatuesCell
        cell.statusesCellViewModel = statusesList.statusesCell![indexPath.row]
        cell.selectionStyle = .None
        return cell
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        // 是否是最后一个cell
        if indexPath.row == (statusesList.statusesCell?.count)! - 1 && !dragUpView.isAnimating() {
            cell.contentView.backgroundColor = UIColor.whiteColor()
            // 如果是那么就上拉加载
            loadMoreData(true, isPullDown: false)
        }
    }
    
}
